<?php
declare (strict_types=1);

namespace app\api\controller\master;

use app\Api\controller\Order;
use app\api\model\Goods;
use app\Api\model\Orders;
use app\serve\controller\Token;
use think\facade\Db;
use think\Request;

class ChargeOff
{
    /**
     * @param $order_no '订单编号'
     * 查询待审核的商品
     */
    public function chargeOffGoods($order_no)
    {
        //扫描二维码传过来的订单编号
        $order_info = Orders::where('order_no',$order_no)->find();
        if (!$order_info){
            return json(['code'=>10003,'msg'=>'暂未查到该订单信息,请联系商家','data'=>[]]);
        }
        //从订单中取出商品id
        $goods_id = $order_info->goods_id;
        //查询出来的商品信息
        $goods_data = Goods::where('good_id',$goods_id)->find();
        if (!$goods_data){
            $data = [];
            return json(['code'=>10002,'msg'=>'未查到商品信息,请联系商家','data'=>$data]);
        }
        //订单付款金额
        $goods_price = $order_info->goods_price;
        //封面图
        $goods_banner = $goods_data->good_banner;
        //商品名称
        $goods_name = $goods_data->goods_name;
        //组装数据
        $data = [
            'goods_banner' => $goods_banner,
            'goods_name' => $goods_name,
            'goods_price' => $goods_price
        ];
        return json(['code'=>10001,'msg'=>'请求成功','data'=>$data]);
    }

    /**
     * 确认核销
     */
    public function affirm(Request $request)
    {
        //第一步先取token
        $token = $request->header('token');
        //jwt进行校验token
        $res = (new Token())->chekToken($token);
        if ($res['code'] != 1) {
            return json(['error_code' => 10002, 'msg' => $res['msg'], 'data' => ''], 400);
        }
        $charge_off_member_id = $res['data']->uid;
        $order_no = $request->param('order_no');
        $data = [
            'charge_off_member_id' => $charge_off_member_id,
            'order_no' => $order_no
        ];
        Db::startTrans();
        try {
            $charge_off_model = new \app\admin\model\ChargeOff();
            //添加核销记录
            $charge_off_res = $charge_off_model->orderAll($data);
            if ($charge_off_res){
                //核销返回订单号
                $order_no = $charge_off_res;
                //调用修改订单状态接口
                $order_model = new Order();
                $order_model->changeChargeOffStatus($order_no);
                Db::commit();
                return json(['code'=>10001,'msg'=>'核销成功','data'=>[]]);
            }
            Db::rollback();
            return json(['code'=>10002,'msg'=>'核销失败','data'=>[]]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>10002,'msg'=>'核销失败','data'=>[]]);
        }
    }
}
